package cn.dgiot.fd.service.impl;

import java.util.ArrayList;
import java.util.List;
import java.util.UUID;

import cn.dgiot.fd.service.IDeviceStateService;
import org.springframework.beans.factory.annotation.Autowired;
import org.springframework.stereotype.Service;

import cn.dgiot.fd.dao.IPropertiesSetDAO;
import cn.dgiot.fd.model.DeviceStateModel;
import cn.dgiot.fd.model.PropertiesSetModel;
import cn.dgiot.fd.service.IPropertiesSetService;

/**
 * [属性设置记录]
 * @author
 *
 */
@Service
public class PropertiesSetServiceImpl implements IPropertiesSetService{

	@Autowired
	private IPropertiesSetDAO propertiesSetDAO;

	@Autowired
	private IDeviceStateService deviceStateService;
	
	@Override
	public PropertiesSetModel getPropertiesSet(PropertiesSetModel propertiesSetModel) {
		// TODO Auto-generated method stub
		return propertiesSetDAO.getPropertiesSet(propertiesSetModel);
	}

	@Override
	public void insertPropertiesSet(PropertiesSetModel propertiesSetModel) {
		List<String> deviceNames = propertiesSetModel.getDeviceNames();
		List<PropertiesSetModel> propertiesSetModelList = new ArrayList<PropertiesSetModel>();
		for(int i=0;i<deviceNames.size();i++) {
			String deviceName = deviceNames.get(i);
			String productKey = propertiesSetModel.getProductKey();
			PropertiesSetModel result = propertiesSetDAO.getPropertiesSet(new PropertiesSetModel(deviceName, productKey));
			
			PropertiesSetModel param = new PropertiesSetModel();
			param.setDeviceName(deviceName);
			param.setProductKey(productKey);
			param.setMessageId(propertiesSetModel.getMessageId());
			param.setStatus(propertiesSetModel.getStatus());
			param.setCreateTime(propertiesSetModel.getCreateTime());
			if(result != null) {
				propertiesSetDAO.updatePropertiesSet(param);
			}else {
		    	DeviceStateModel deviceStateModel = new DeviceStateModel();
		    	deviceStateModel.setDeviceName(deviceName);
		    	deviceStateModel.setProductKey(propertiesSetModel.getProductKey());
		    	DeviceStateModel deviceStateModelResult = deviceStateService.getDeviceState(deviceStateModel);
				param.setIotId(deviceStateModelResult.getIotId());
				param.setId(UUID.randomUUID().toString().replace("-", ""));
				propertiesSetModelList.add(param);
			}
		}
		if(propertiesSetModelList != null && propertiesSetModelList.size() > 0) {
			propertiesSetDAO.insertPropertiesSet(propertiesSetModelList);
		}
	}

	@Override
	public void updatePropertiesSetStatus(PropertiesSetModel propertiesSetModel) {
		// TODO Auto-generated method stub
		propertiesSetDAO.updatePropertiesSetStatus(propertiesSetModel);
	}

}
